package com.blb.demo;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * 阻塞队列的使用
 */
public class BlockingQueueDemo {

    public static void main(String[] args) throws InterruptedException {
        //缓冲区
        BlockingQueue<Baozi> baozis = new ArrayBlockingQueue<>(100);
        //生产者线程
        new Thread(() -> {
            for (int i = 0; i < 200; i++) {
                //创建数据，添加到阻塞队列
                Baozi baozi = new Baozi(baozis.size() + 1);
                try {
                    baozis.put(baozi);
                    System.out.println(Thread.currentThread().getName()+"生产完成：" + baozi + "，数量：" + baozis.size());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        //消费者线程
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                for (int j = 0; j < 20; j++) {
                    try {
                        //从阻塞队列中取数据
                        Baozi baozi = baozis.take();
                        System.out.println(Thread.currentThread().getName()+"吃了" + baozi + "，数量：" + baozis.size());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }
}
